#!/bin/bash
set -ex

# 配置参数
INSTALL_PREFIX="./out"      # 安装目录
BUILD_DIR="./build"         # 构建目录
PORT=50051                  # 服务端端口
SERVER_EXE="${INSTALL_PREFIX}/bin/server"
CLIENT_EXE="${INSTALL_PREFIX}/bin/client"
SERVER_PID=0
BUILD_TYPE="MinSizeRel"

# 清理函数：停止服务端并清理临时文件
cleanup() {
    if [ ${SERVER_PID} -ne 0 ]; then
        echo "Stopping gRPC server (PID: ${SERVER_PID})..."
        kill ${SERVER_PID} > /dev/null 2>&1
        wait ${SERVER_PID} 2>/dev/null
    fi

    echo "Cleanup complete."
    exit 0
}

# 捕获中断信号，执行清理
trap cleanup SIGINT SIGTERM

# 构建项目
build_project() {
    echo "Building project..."

    # 运行CMake配置
    cmake -S . -B build -G "Ninja"                  \
        -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX}    \
        -DCMAKE_BUILD_TYPE=${BUILD_TYPE}            \
        -DCMAKE_EXPORT_COMPILE_COMMANDS=TRUE        \
        -DCMAKE_C_COMPILER=clang                    \
        -DCMAKE_CXX_COMPILER=clang++

    # 构建项目
    cmake --build build --config ${BUILD_TYPE} -j$(nproc)

    # 安装到指定目录
    echo "Installing to ${INSTALL_PREFIX}..."
    cmake --install build --config ${BUILD_TYPE}
}

# 启动服务端
start_server() {
    echo "Starting gRPC server on port ${PORT}..."
    if [ ! -f ${SERVER_EXE} ]; then
        echo "Error: Server executable not found at ${SERVER_EXE}"
        exit 1
    fi

    ${SERVER_EXE} ${PORT} &
    SERVER_PID=$!

    # 等待服务端启动
    sleep 2
    if ! ps -p ${SERVER_PID} > /dev/null; then
        echo "Error: Failed to start server"
        exit 1
    fi
    echo "Server started with PID: ${SERVER_PID}"
}

# 运行客户端
run_client() {
    echo "Starting gRPC client..."
    if [ ! -f ${CLIENT_EXE} ]; then
        echo "Error: Client executable not found at ${CLIENT_EXE}"
        cleanup
        exit 1
    fi

    echo "Connecting to server at localhost:${PORT}..."
    ${CLIENT_EXE} localhost ${PORT}

    # 客户端退出后等待用户输入再关闭服务端
    echo -e "\nClient exited."
}

# 主流程
main() {
    echo "=== gRPC Auto Build & Run Script ==="
    build_project
    start_server
    run_client
    cleanup
}

# 启动主流程
main
